package com.finance.system.configure.websecurity;

import com.finance.system.support.bean.JwtToken;
import com.finance.system.support.utils.JwtTokenUtil;
import com.finance.system.user.entity.JwtPayload;
import com.finance.system.user.entity.UserEntity;
import com.finance.system.user.entity.UserInfo;
import com.finance.system.user.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class FinanceAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    public static String TOKEN_KEY = "Authentication";


    @Autowired
    private JwtTokenUtil jwtTokenUtil;
    @Autowired
    private IUserService userService;


    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
                                        Authentication authentication) {
        User principal = (User) authentication.getPrincipal();

        UserEntity user = userService.getByPhone(principal.getUsername());

        JwtPayload payload = new JwtPayload(user.getId(),user.getUserName(),user.getPhone(),
                user.getEmail(),null,null);

        JwtToken token = jwtTokenUtil.generateToken(payload);
        response.setHeader(TOKEN_KEY, token.getJwt());
    }
}
